package com.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.dao.ICommissionerDao;
import com.dao.entity.Commissioner;
import com.dao.entity.base.BaseEntity;
import com.service.ICommissionerService;
import com.utils.commons.CopyProperties;
import com.utils.commons.Encoder;
import com.utils.commons.PageUtils;
import com.utils.enums.ENUM_ROLES;
import com.utils.enums.ENUM_SUCESS;


@Service
public class CommissionerServiceImpl implements ICommissionerService {
	
	@Autowired
    private ICommissionerDao commissionerDao;

	@Override
	public Commissioner login(String username, String password) {
		return commissionerDao.findByAccountAndPasswordAndIsApproval(username, Encoder.MD5FreeHex(password), ENUM_SUCESS.YES.value);
	}

	@Override
	public Commissioner addAdmin() {
		Commissioner user = new Commissioner();
		user.setPassword(Encoder.MD5FreeHex(BaseEntity.ADMIN_PSW));
		user.setUserName(BaseEntity.ADMIN);
		user.setAccount(BaseEntity.ADMIN);
		user.setIsApproval(ENUM_SUCESS.YES.value);
		user.setRole(ENUM_ROLES.ADMINISTRATOR.value);
		return commissionerDao.save(user);
	}

	@Override
	public Commissioner findAdmin() {
		Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(0, 1, sort);
        Page<Commissioner> pages = commissionerDao.findByUserName("admin", pageable);
        for (Commissioner user : pages) {
        	return user;
        }
		return null;
	}
	
	@Override
	public Page<Commissioner> findUserByCondition(Commissioner c, Integer page, Integer size, String orderBy) {
		Pageable pageable;
		if(orderBy != null && orderBy.length() > 0) {
			pageable = PageUtils.toPageable(page, size, Sort.Direction.DESC, orderBy);
		}else {
			pageable = PageUtils.toPageable(page, size);
		}
		Map<String, Object> values = new HashMap<String, Object>();
		StringBuffer queryString = new StringBuffer("SELECT dc.id as id, dc.account as account, dc.userName as userName, dc.password as password, ")
				.append("dc.role as role, dc.idCard as idCard, ")
				.append("dc.openId as openId, dc.isApproval as isApproval, ")
				.append("dc.sex as sex, dc.createdate as createdate, dc.updatedate as updatedate, dc.isdelete as isdelete\r\n")
				.append("FROM loan_commissioner dc\r\n")
				.append("where 1=1 ");
		if(!StringUtils.isEmpty(c.getUserName())) {
			values.put("userName", "%"+c.getUserName()+"%");
			queryString.append(" and dc.userName like :userName\r\n");
		}
		if(!StringUtils.isEmpty(c.getIdCard())) {
			values.put("idCard", "%"+c.getIdCard()+"%");
			queryString.append(" and dc.idCard like :idCard\r\n");
		}
		if(!ObjectUtils.isEmpty(c.getIsApproval())) {
			values.put("isApproval", c.getIsApproval());
			queryString.append(" and dc.isApproval = :isApproval\r\n");
		}
		if(!ObjectUtils.isEmpty(c.getRole())) {
			values.put("role", c.getRole());
			queryString.append(" and dc.role = :role\r\n");
		}
		StringBuffer countString = new StringBuffer("select count(1) from (").append(queryString).append(") a");
		return commissionerDao.sqlQuery(queryString.toString(), countString.toString(), values, pageable);
	}

	@Override
	public Commissioner findUserById(Long id) {
		return commissionerDao.findById(id).orElse(new Commissioner());
	}

	@Override
	public Commissioner saveUser(Commissioner user) {
		if(ObjectUtils.isEmpty(user)) {
			return null;
		}
		if(!ObjectUtils.isEmpty(user.getPassword())){
			user.setPassword(Encoder.MD5FreeHex(user.getPassword()));
		}
		Commissioner old = commissionerDao.findById(user.getId()).get();
		CopyProperties.nullNotCopy(user, old);
		return commissionerDao.save(old);
	}

	@Override
	public void deleteUser(Long id) {
		commissionerDao.deleteById(id);
	}

	@Override
	public Commissioner findCommis(Commissioner commis) {
		if(commis.getId() != null) {
			return commissionerDao.findById(commis.getId()).orElse(new Commissioner());
		}
		if(commis.getOpenId() != null) {
			return commissionerDao.findByOpenIdAndRole(commis.getOpenId(), ENUM_ROLES.COMMISSIONER.value);
		}
		return new Commissioner();
	}

	@Override
	public void approvalCommis(Long id) {
		commissionerDao.findById(id).ifPresent(e ->{
			e.setIsApproval(ENUM_SUCESS.YES.value);
			commissionerDao.save(e);
		});
	}

}
